package com.atguigu.srb.sms.service.impl;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.atguigu.srb.common.exception.Assert;
import com.atguigu.srb.common.exception.BusinessException;
import com.atguigu.srb.common.result.ResponseEnum;
import com.atguigu.srb.sms.service.SmsService;
import com.atguigu.srb.sms.utils.SmsProperties;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author lwm1435@163.com
 * @date 2022-02-11 17:32
 * @description
 */
@Slf4j
@Service
public class SmsServiceImpl implements SmsService {
    //发送阿里云测试短信
    @Override
    public void sendSms(String mobile, Map<String,Object> param) {
        Client client = null;
        Gson gson = new Gson();
        String paramJson = gson.toJson(param);
        try {
            client = createClient(SmsProperties.KEY_ID, SmsProperties.KEY_SECRET);
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setSignName(SmsProperties.SIGN_NAME)
                    .setTemplateCode(SmsProperties.TEMPLATE_CODE)
                    .setPhoneNumbers(mobile)
                    .setTemplateParam(paramJson);
            //发送验证码
            SendSmsResponse response = client.sendSms(sendSmsRequest);
            String code = response.getBody().code;

            //断言抛出自定义异常短信发送频繁
//            {"code":"isv.BUSINESS_LIMIT_CONTROL","message":"触发分钟级流控Permits:1","requestId":"6BCF0188-1108-5380-BE23-3FDC979D737D"}
            Assert.notEquals("isv.BUSINESS_LIMIT_CONTROL", code, ResponseEnum.ALIYUN_SMS_LIMIT_CONTROL_ERROR );

            //断言结果不为OK抛出异常返回message
            Assert.equals("OK",code, ResponseEnum.ALIYUN_SMS_ERROR);
//            {   返回的成功样例
//                "bizId": "642517643014274291^0",
//                "code": "OK",
//                "message": "OK",
//                "requestId": "F69136B4-9A32-5FF3-BDF9-DD00BE760AAD"
//            }
        } catch (Exception e) {
            log.error("发送短信失败");
            throw new BusinessException(ResponseEnum.ALIYUN_SMS_LIMIT_CONTROL_ERROR,e);
        }

    }
    /**
     * 使用AK&SK初始化账号Client
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    private  Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }
}
